package com.example.player.service.impl;

import com.example.player.entity.User;
import com.example.player.entity.dto.UserLoginDTO;
import com.example.player.entity.dto.UserRegDTO;
import com.example.player.ex.ServiceException;
import com.example.player.mapper.UserMapper;
import com.example.player.service.IUserService;
import com.example.player.util.GlobalPasswordEncoder;
import com.example.player.web.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author fendou2021
 * @create 2022-04-17 21:12
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(UserRegDTO userRegDTO) {
        User u = userMapper.getByUsername(userRegDTO.getUsername());

        if (u != null) {
            throw new ServiceException("用户名已存在!", JsonResult.State.CONFLICTED);
        }

        String rawPassword = userRegDTO.getPassword();
        String encodedPassword = GlobalPasswordEncoder.encode(rawPassword);

        User user = new User();
        user.setUsername(userRegDTO.getUsername());
        user.setPassword(encodedPassword);
        user.setGmtCreate(LocalDateTime.now());
        user.setGmtModified(LocalDateTime.now());
        int rows = userMapper.insert(user);
        if (rows != 1) {
            throw new ServiceException("服务器忙,请稍后再试!", JsonResult.State.SERVER_ERROR);
        }
    }

    @Override
    public void login(UserLoginDTO userLoginDTO, HttpSession session) {
        User u = userMapper.getByUsername(userLoginDTO.getUsername());
        if (u == null) {
            throw new ServiceException("用户名不存在!", JsonResult.State.NOT_FOUND);
        }
        String rawPassword = userLoginDTO.getPassword();
        String encodedPassword = GlobalPasswordEncoder.encode(rawPassword);
        if (!u.getPassword().equals(encodedPassword)) {
            throw new ServiceException("密码错误!", JsonResult.State.NOT_FOUND);
        }
        session.setAttribute("user",u);
    }

    @Override
    public void logout(HttpSession session) {
        session.removeAttribute("user");
    }

    @Override
    public User getCurrentUser(HttpSession session) {
        return (User) session.getAttribute("user");
    }
}
